package com.sl.leetcode;


import java.lang.reflect.Method;

/**
 * Created by lisulong on 2019/5/28.
 * 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * <p>
 * 示例：
 * <p>
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 */
public class Solution21 {
    public ListNode method1(ListNode l1, ListNode l2) {
        ListNode result = null;
        ListNode resultIndex = null;
        while (true) {
            if (l1.val >= l2.val) {
                if (result == null) result = l2;
                else resultIndex.next = l2;
                resultIndex = l2;
                l2 = l2.next;
            } else {
                if (result == null) result = l1;
                else resultIndex.next = l1;
                resultIndex = l1;
                l1 = l1.next;
            }
            if (l1 == null) {
                resultIndex.next = l2;
                break;
            }
            if (l2 == null) {
                resultIndex.next = l1;
                break;
            }

        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        Class<Solution21> clz = Solution21.class;
        Object obj = clz.newInstance();
        Method executeMethod;
        for (int i = 1; i <= 1; i++) {
            long startTime = System.nanoTime();
            executeMethod = clz.getMethod("method" + i, ListNode.class, ListNode.class);
            ListNode n1 = new ListNode(1);
            ListNode nn1 = new ListNode(1);
            ListNode n2 = new ListNode(2);
            ListNode n3 = new ListNode(3);
            ListNode n4 = new ListNode(4);
            ListNode nn4 = new ListNode(4);
            ListNode l1=n1;
            n1.next=n3;
            n3.next=n4;
            ListNode l2=nn1;
            nn1.next=n2;
            n2.next=nn4;
            ListNode l = (ListNode)executeMethod.invoke(obj, l1, l2);
            do {
                System.out.println(l.val+"->");
                l=l.next;
            }while (l.next!=null);
            
            //System.out.println(executeMethod.invoke(obj, );//数组做为参数的，需要使用new Object[]{}包一层
            System.out.println("====耗时：" + (System.nanoTime() - startTime));
        }
    }
}
